import React, {Component} from "react";
import {Table, Input, InputNumber, Button, Modal} from "antd";
import {API_URL} from "../constants";
import ImageUpload from "../utilComponent/ImageUpload";
import {getCrmFields} from "../util/util";

const {TextArea} = Input;

const ZOHO = window.ZOHO;

class QuoteTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            columns: [],
            moduleName: this.props.moduleName,
            scrollWidth: 0,
            initObj: {},
            selectedRowKeys: [],
            shouldTriggerOnChange: true,
            loading: false,
            modalVisible: false,
            productData: [],
            productColumns: [],
            selectedProductRowKeys: [],
            parentModuleName: this.props.parentModuleName,
            selectedData: [],
            readOnlyFields: ['Name', 'AccountOrderNo', 'Product', 'Foreignsacontract', 'AccountprtNo', 'internalcode', 'Productname', 'Chineseingredients', 'Chinesespecification', 'Unit', 'Make', 'Ptrequirements_material', 'Englishname', 'Specification', 'Packaginunit'],
        }

    }

    async componentDidMount() {
        this.setState({loading: true}, this.initFields);
    }

    async initFields() {
        const {moduleName, parentModuleName, readOnlyFields} = this.state;
        let columns = [];
        let fields = await getCrmFields(moduleName);
        console.log(fields)
        let obj = {};
        let productData = [];
        let productColumns = []
        for (const field of fields) {
            if (!field.view_type.create || field.data_type === 'ownerlookup') {
                continue;
            }
            if (field.data_type === "text") {
                obj[field.api_name] = "";
            }

            if (field.data_type === "imageupload") {
                obj[field.api_name] = [];
            }
            if (field.data_type === "double") {
                obj[field.api_name] = 0;
            }

            if (field.data_type === "integer") {
                obj[field.api_name] = 0;
            }
            let hidden = false
            if (readOnlyFields.includes(field.api_name)) {
                field.read_only = true;
            }
            let column = {
                title: field.field_label,
                dataIndex: field.api_name,
                key: field.api_name,
                type: field.data_type,
                className: hidden ? 'hidden-column' : "",
                render: (text, record, index) => this.renderCell(field, text, record, index)
            }
            columns.push(column)
        }
        obj["id"] = "";

        console.log(obj)
        const scrollWidth = columns.length * 200;
        let dataSource = [];
        if (window.id !== undefined) {
            let req_data = {
                parameters: {},
                method: "GET",
                url: API_URL + `/crm/v3/${moduleName}/search?criteria=(${parentModuleName}.id:equals:${window.id})`,
                param_type: 1,
            };
            console.log(columns)
            const dataIndexArray = columns.map(item => item.dataIndex);
            dataIndexArray.push("id");
            await ZOHO.CRM.CONNECTION.invoke("crm", req_data).then((data) => {
                console.log(data)
                let detail = data.details.statusMessage.data;
                dataSource = detail?.map(item => {
                    return dataIndexArray.reduce((obj, dataIndex, currentIndex) => {
                        if (dataIndex === "Picture") {
                            item[dataIndex].map((a, index) => {
                                item[dataIndex][index].Description = "";
                            })
                        }
                        obj[dataIndex] = item[dataIndex];
                        if (dataIndex === "Name") {
                            obj["key"] = item[dataIndex] ? item[dataIndex] : currentIndex
                        }
                        if (dataIndex === "Quantity") {
                            obj["MaxQuantity"] = item["Quantity"] + item["PurchaseQty"]
                        }
                        return obj;
                    }, {});
                });
            });
        }
        this.setState({
            columns: columns,
            scrollWidth: scrollWidth,
            initObj: obj,
            data: dataSource,
            loading: false,
            productColumns: productColumns,
            productData: productData,
        });

    }

    renderCell = (field, text, record, index) => {
        let editable = field.api_name === 'PurchaseQty' || field.api_name === 'Quantity' || field.api_name === 'PurchaseAmount';
        let children = null;
        if (editable) {
            if (field.api_name === 'PurchaseQty') {
                children = <InputNumber
                    step={1}
                    max={record['MaxQuantity']}
                    min={0}
                    value={record[field.api_name]}
                    onChange={(e) => this.handleCellChange(e, field, index)}
                />;
            }
            if (field.api_name === 'Quantity') {
                let result = record['MaxQuantity'] - record['PurchaseQty'];
                try {
                    result = Number(result.toFixed(0))
                    // 检查formula字段的值是否发生变化
                    if (record[field.api_name] !== result) {
                        // 触发onChange事件
                        // this.handleCellChange(result, field, index);
                    }
                } catch (error) {
                    console.error(`计算公式出错：${error}`);
                }
                children = <InputNumber
                    step={1}
                    disabled={true}
                    min={0}
                    value={record[field.api_name]}
                    onChange={(e) => this.handleCellChange(e, field, index)}
                />;
            }
            if (field.api_name === 'PurchaseAmount') {
                let result = record['Purchaseunitprice'] * record['PurchaseQty'];
                try {
                    result = Number(result.toFixed(0))
                    // 检查formula字段的值是否发生变化
                    if (record[field.api_name] !== result) {
                        // 触发onChange事件
                        // this.handleCellChange(result, field, index);
                    }
                } catch (error) {
                    console.error(`计算公式出错：${error}`);
                }
                children = <InputNumber
                    step={1}
                    disabled={true}
                    min={0}
                    value={result}
                    onChange={(e) => this.handleCellChange(e, field, index)}
                />;
            }

        }
        return editable ? children : record[field.api_name];
    };

    handleCellChange = (newValue, field, index) => {
        const {data} = this.state;
        const newData = [...data];
        if (field.data_type === "text" || field.data_type === "double" || field.data_type === "integer" || field.data_type === "textarea") {
            newData[index][field.api_name] = newValue;
        }

        if (field.data_type === "lookup") {
            newData[index][field.api_name] = {
                id: newValue.value,
                name: newValue.label
            }
        }
        console.log(newData)
        this.setState({
            data: newData,
        });

    };


    removeRow = (index) => {
        const {data, selectedRowKeys, selectedData} = this.state;
        console.log(selectedData)
        const newData = data.filter(item => !selectedRowKeys.includes(item.key)); // 创建一个新的数组，复制原始数据
        this.props.updatecontractData(selectedData.filter(item => selectedRowKeys.includes(item.key)))
        this.setState({data: newData, selectedRowKeys: []});
    }

    onSelectChange = (newselectedRowKeys) => {
        console.log(newselectedRowKeys)
        this.setState({selectedRowKeys: newselectedRowKeys});
    };


    updateInvoiceDatas = (newInvoiceDatas, newSelectedData) => {
        // 在这个方法中，你可以更新InvoiceTable组件的内部状态，或者通过修改props来触发重新渲染
        console.log(newInvoiceDatas)
        this.setState({data: newInvoiceDatas, selectedData: newSelectedData})
    };

    getInvoiceDatas = () => {
        const {data} = this.state
        return data;
    }

    render() {
        const {
            columns,
            data,
            scrollWidth,
            selectedRowKeys,
            loading,
            modalVisible,
            productData,
            productColumns,
            selectedProductRowKeys,
        } = this.state;
        return (
            <div>
                <div>
                    <div style={{
                        display: 'flex',
                        justifyContent: 'flex-end',
                        marginBottom: 16,
                        marginTop: 16,
                        marginRight: 16
                    }}>
                        <Button onClick={this.removeRow} loading={loading} type="primary" danger>删除一行</Button>
                    </div>

                </div>

                <Modal

                    open={modalVisible}
                    onCancel={this.handleCloseModal}
                    onOk={this.handleOkModal}
                    cancelText={"取消"}

                    okText={"确认"}
                    centered
                >
                    <Table
                        rowSelection={{
                            fixed: true,
                            selectedRowKeys: selectedProductRowKeys, // 多选表格选中行的 keys 数组
                            onChange: this.onProductSelectChange, // 选中行发生变化时的回调函数
                        }} columns={productColumns} dataSource={productData} scroll={{x: scrollWidth}}/>
                </Modal>
                <Table
                    rowSelection={{
                        fixed: true,
                        selectedRowKeys: selectedRowKeys, // 多选表格选中行的 keys 数组
                        onChange: this.onSelectChange, // 选中行发生变化时的回调函数
                    }}
                    loading={loading}
                    columns={columns}
                    dataSource={data}
                    scroll={{x: scrollWidth}}/>
            </div>

        );
    }
}

export default QuoteTable;